package logic

import (
	"context"
	"fmt"
	"sus/models/cache"
	"sus/models/mysql"
	"sus/pkg"

	"sus/internal/svc"
	"sus/sus"

	"github.com/zeromicro/go-zero/core/logx"
)

type LonginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLonginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LonginLogic {
	return &LonginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LonginLogic) Longin(in *sus.LonginRequest) (*sus.LonginResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Rdb.Get(l.ctx, "sendSms"+in.Account)
	if get.Val() != in.SendCode {
		return nil, fmt.Errorf("验证码错误")
	}
	var err error
	var u mysql.User
	u.Account = in.Account
	u.Password = pkg.Md5(in.Password)

	if err = u.GetUserInfoById(); err != nil {
		logx.Error("用户不存在")
		return nil, err
	}
	if u.ID == 0 {
		if err = u.CreateUserInfo(); err != nil {
			logx.Error("数据库联机失败")
		}
	}

	return &sus.LonginResponse{
		Id: int64(u.ID),
	}, nil
}
